package top.infopub.mgr.bpa.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.bpa.BpaPublicProInfoDto;
import top.infopub.dto.bpa.DeductionRecordQueryDto;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.mgr.bpa.dao.DeductionRecordMapper;
import top.infopub.mgr.bpa.jsonVo.DeductionRecordDetailJsonVo;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.service.DeductionRecordService;
import top.infopub.mgr.bpa.vo.DeductionRecordOtherVo;
import top.infopub.mgr.bpa.vo.DeductionRecordVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.ProjectInfoService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.util.FileAttrUtils;
import top.infopub.model.bpa.DeductionRecord;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.util.IdFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 扣款记录 BPA_DEDUCTION_RECORD
 * @Author: xieyong
 * @Date: 2021/6/20 15:38
 * @Since 1.0
 **/
@Service
public class DeductionRecordServiceImpl implements DeductionRecordService {
    @Autowired
    private DeductionRecordMapper deductionRecordMapper;
    //项目基础信息查询服务
    @Autowired
    private ProjectInfoService projectInfoService;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private BpaProcessManageService bpaProcessManageService;
    @Autowired
    private SetupProService setupProService;

    @Override
    public Page<DeductionRecordVo> selectByDomainWhere(Page<DeductionRecordVo> page, DeductionRecordQueryDto deductionRecordQueryDto) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return deductionRecordMapper.selectByDomainWhere(deductionRecordQueryDto);
    }

    @Override
    public DeductionRecordDetailJsonVo queryDetailById(String id) {
        DeductionRecordDetailJsonVo detailJsonVo = new DeductionRecordDetailJsonVo();
        if (StringUtils.isEmpty(id)) {
            detailJsonVo = createDetail(detailJsonVo);
        } else {
            detailJsonVo = createDetailWithId(id, detailJsonVo);
        }
        return detailJsonVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RspVo save(DeductionRecordDetailJsonVo detailJsonVo, Integer submitType) {
        DeductionRecordOtherVo deductionRecordOtherVo = detailJsonVo.getInfo();
        DeductionRecord payment = new DeductionRecord();
        BeanUtils.copyProperties(deductionRecordOtherVo, payment);
        payment.setUptBy(SessionUserUtils.getSessionUserId());
        payment.setUptTime(new Date());
        if (StringUtils.isEmpty(payment.getId())) {
            payment.setAddBy(SessionUserUtils.getSessionUserId());
            payment.setAddTime(new Date());
            payment.setCodes(IdFactory.getUUIDUpper());
            //新增
            deductionRecordMapper.insertSelective(payment);
        } else {
            //校验数据是否存在
            DeductionRecord tmpDr = deductionRecordMapper.selectByPrimaryKey(payment.getId());
            if (tmpDr == null) return RspVo.getFailureResponse(400, "商务成本支付数据不存在");
            //判断审批状态
            if (StringUtils.isNotBlank(tmpDr.getProcessStatus())
                    && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpDr.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpDr.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            //编辑
            deductionRecordMapper.updateByPrimaryKeySelective(payment);
            payment.setOaId(tmpDr.getOaId());
        }

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if (detailJsonVo.getFileAtt() != null) {
            String[] fileAtt = detailJsonVo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = FileAttrUtils.createProjectFileAtta(payment.getId(), file);
                attachmentList.add(attachment);
            }
        }
        projectAttachmentDao.deleteByWhere(payment.getId(), ProjectFileTypeEnum.FILE_TYPE144.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (1 == submitType) {
            if (StringUtils.isNotBlank(payment.getOaId())) {
                oaFlowService.finishOA(payment.getOaId());
            }
            DeductionRecordDetailJsonVo bizPlanJson = this.queryDetailById(payment.getId());
            String json = JSON.toJSONString(bizPlanJson);

            bpaProcessManageService.sendProcess(BpaProcessDetailTypeEnum.PRO_NODE_TYPE30, json, payment.getId(), payment.getProCode(), SessionUserUtils.getSessionAttributeForUserDtl());
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public DeductionRecord selectByPrimaryKey(String id) {
        return deductionRecordMapper.selectByPrimaryKey(id);
    }

    private DeductionRecordDetailJsonVo createDetailWithId(String id, DeductionRecordDetailJsonVo detailJsonVo) {
        /** 1、扣款记录基础信息 **/
        DeductionRecord deductionRecord = deductionRecordMapper.selectByPrimaryKey(id);
        DeductionRecordOtherVo paymentVo = new DeductionRecordOtherVo();
        BeanUtils.copyProperties(deductionRecord, paymentVo);
        BpaPublicProInfoDto proInfoDto = projectInfoService.queryBpaProInfoByProCode(deductionRecord.getProCode());
        BeanUtils.copyProperties(proInfoDto, paymentVo);
        detailJsonVo.setInfo(paymentVo);

        /** 2、项目下拉框 **/
//        List<Map<String, String>> listMap = new ArrayList<>();
//        Map<String, String> map = new HashMap<>();
//        map.put(paymentVo.getProCode(), paymentVo.getProName());
//        listMap.add(map);
//        detailJsonVo.setProNameAndId(listMap);

        /** 3、附件信息表 **/
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(id, ProjectFileTypeEnum.FILE_TYPE147.getCode(), null);
        detailJsonVo.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));

        return detailJsonVo;
    }

    private DeductionRecordDetailJsonVo createDetail(DeductionRecordDetailJsonVo detailJsonVo) {
        //返回所有的项目code和name
        detailJsonVo.setProInfoList(setupProService.queryPublicProInfo());
        return detailJsonVo;
    }
}
